package com.gxuwz.weather;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.gxuwz.weather.adapter.WeatherPagerAdapter;
import com.gxuwz.weather.citymanager.CityManagerActivity;
import com.gxuwz.weather.config.JsonRead;
import com.gxuwz.weather.config.RequestDemo1;
import com.gxuwz.weather.db.DBHelper;
import com.gxuwz.weather.model.Weathernow;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    ImageView addCityIv, moreIv;
    ViewPager2 viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager = findViewById(R.id.pager_weather);
        // 加载 myarea 数据
        loadMyAreaData(new DataCallback<List<Map<String, String>>>() {
            @Override
            public void onDataLoaded(List<Map<String, String>> myAreaData) {
                // 初始化 JsonRead 对象
                JsonRead jsonRead = new JsonRead();
                // 在子线程中发送天气请求并更新对应的天气界面数据
                sendWeatherRequest(myAreaData, jsonRead);
            }
        });

        addCityIv = findViewById(R.id.main_iv_manager);
        moreIv = findViewById(R.id.main_iv_more);
        addCityIv.setOnClickListener(this);
        moreIv.setOnClickListener(this);
    }

    @SuppressLint("Range")
    private void loadMyAreaData(final DataCallback<List<Map<String, String>>> callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBHelper dbHelper = new DBHelper(MainActivity.this);
                SQLiteDatabase db = dbHelper.getReadableDatabase();
                Cursor cursor = db.query("myarea", new String[]{"areaCn"}, null, null, null, null, null);

                List<Map<String, String>> resultList = new ArrayList<>();
                while (cursor.moveToNext()) {
                    Map<String, String> cityInfo = new HashMap<>();
                    cityInfo.put("areaCn", cursor.getString(cursor.getColumnIndex("areaCn")));
                    resultList.add(cityInfo);
                }
                cursor.close();

                // 在主线程中回调结果
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onDataLoaded(resultList);
                    }
                });
            }
        }).start();
    }

    private void sendWeatherRequest(List<Map<String, String>> myAreaData, JsonRead jsonRead) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int i = 0; i < myAreaData.size(); i++) {
                        Map<String, String> areaData = myAreaData.get(i);
                        String areaCn = areaData.get("areaCn");
                        String response = RequestDemo1.getWeatherData(areaCn);
                        Log.d("WeatherRequest", "Response for " + areaCn + ": " + response);
                        jsonRead.updateWeatherData(response);
                    }

                    // 在主线程中更新 ViewPager 的适配器
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            List<Weathernow> weatherList = jsonRead.getWeatherList();
                            WeatherPagerAdapter adapter = new WeatherPagerAdapter(MainActivity.this, weatherList);
                            viewPager.setAdapter(adapter);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void loadJSONFromAsset(final String fileName, final DataCallback<String> callback) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String json = null;
                try {
                    InputStream is = getAssets().open(fileName);
                    int size = is.available();
                    byte[] buffer = new byte[size];
                    is.read(buffer);
                    is.close();
                    json = new String(buffer, "UTF-8");
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

                // 在主线程中回调结果
                final String finalJson = json;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        callback.onDataLoaded(finalJson);
                    }
                });
            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.main_iv_manager:
                intent.setClass(MainActivity.this, CityManagerActivity.class);
                break;
            case R.id.main_iv_more:
                intent.setClass(MainActivity.this, MoreActivity.class);
                break;
        }
        startActivity(intent);
    }

    // 定义回调接口
    interface DataCallback<T> {
        void onDataLoaded(T data);
    }
}